﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using pTools.cMethods;
using Flurl;
using Flurl.Http;
using System.Configuration;
using Newtonsoft.Json;
using RJCP.IO.Ports;
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid.Columns;
using pTools.PrintTable;
using DevExpress.XtraGrid;
using System.Diagnostics;
using System.IO;
using System.Management;
using System.Threading;
using Entity.DbEntity;
using Newtonsoft.Json.Serialization;
using DevExpress.XtraLayout;
using System.IO.Compression;
using ExtensionMethods;
using DevExpress.XtraEditors.Repository;
using System.Text.RegularExpressions;


namespace pTools.TuQiangPrint
{
    public partial class ProductionPrint : DevExpress.XtraEditors.XtraForm
    {
        DBHelper db = new DBHelper();
        HttpAgreement http = new HttpAgreement();

        SerialPortStream serial;
        string BaseCode = CommonMethods.baseCode;
        TxtLogHelper txt = new TxtLogHelper();


        List<PrintPrepareModel> ppms = new List<PrintPrepareModel>() { };
        List<ProductionPlan> pps = new List<ProductionPlan>() { };

        List<PrintModel> printModels = new List<PrintModel>();

        bool loopFlag = true;   //关闭串口时为true

        public ProductionPrint()
        {
            InitializeComponent();
        }

        private void ProductionPrint_Load(object sender, EventArgs e)
        {
            try
            {
                cbIsPrint.Checked = false;
                //loadPlan();//生产计划
                GetData();  //获取默认显示数据
                GetBoxWeightList();//轴管重量
                GetWareHouse();//仓库
                GetTeams();//获得班次
                tb_Date.Text = DateTime.Now.ToString("yyyy-MM-dd");

                LoadPrinterInfo();

                StartSerialReading();

                LoadProgramVersion();

                // 检查更新
                Task.Run(() =>
                {
                    while (true)
                    {
                        CheckVersion();
                        Thread.Sleep(5000);
                    }
                });

                //TestRowHeight();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("加载错误：" + ex.Message);
            }
        }

        // 加载程序版本号
        void LoadProgramVersion()
        {
            //label_version.Text += Application.ProductVersion.ToString();
            barStaticItem_Version.Caption = Application.ProductVersion;
        }

        //获的固定数据
        void GetData()
        {
            var DatasSql = @"select parCode,parName,parValue from [sys_parameters_info] 
where partype = 'cuspar' and enable = 'open' and isDel = 0;";
            var datas = db.getData(DatasSql);
            foreach (DataRow item in datas.Rows)
            {
                if (item["parCode"].ToString() == "isYaGuang")//是否压光
                {
                    if(item["parValue"].ToString() == "是")
                    {
                        yaGuang.Checked = true;
                    }
                    else
                    {
                        yaGuang.Checked = false;
                    }
                }
                else if (item["parCode"].ToString() == "mIngredients")//主要成分
                {
                    tb_mIng.Text = item["parValue"].ToString();
                }
                else if (item["parCode"].ToString() == "grade")//等级
                {
                    tb_grade.Text = item["parValue"].ToString();
                }
                else if (item["parCode"].ToString() == "standard")//执行标准
                {
                    tb_standard.Text = item["parValue"].ToString();
                }
                else if (item["parCode"].ToString() == "address")//地址
                {
                    tb_address.Text = item["parValue"].ToString();
                }
                else if (item["parCode"].ToString() == "phoneNum")//电话
                {
                    tb_phone.Text = item["parValue"].ToString();
                }
            }
        }

        // 获取管轴重量 
        void GetBoxWeightList()//1
        {
            var boxWeightSql = @"select cCode,cName from [fun_CommonData_Info] 
where cType = 'TubeWeight' and parentCode = '3' and isDel = 0 and [status] = 'Y';";
            var displayDt = db.getData(boxWeightSql);

            cb_boxWeight.ValueMember = "cCode";
            cb_boxWeight.DisplayMember = "cName";

            cb_boxWeight.DataSource = displayDt;
        }

        // 获取仓库
        void GetWareHouse()//1
        {
            try
            {
                var boxWeightSql = @"select houseCode,houseName from [fun_WareHouse_Info] 
where isDel = 0 and [status] = 'open';";
                var displayDt = db.getData(boxWeightSql);

                tb_wareHouse.DataSource = displayDt;
                tb_wareHouse.ValueMember = "houseCode";
                tb_wareHouse.DisplayMember = "houseName";
                tb_wareHouse.SelectedIndex = 1;

               
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
            
        }

        // 获取班次
        void GetTeams()//1
        {
            var boxWeightSql = @"select depCode,depName from sys_DepartMent_Info where isDel = 0 and status = 'Y';";
            var displayDt = db.getData(boxWeightSql);

            teams.ValueMember = "depCode";
            teams.DisplayMember = "depName";

            teams.DataSource = displayDt;
        }

        // 加载打印机设备所需的相关数据
        void LoadPrinterInfo()
        {
            // 加载模板
            CommonMethods.loadPrintTemplte(cb_0_Template);
            // 加载打印机
            CommonMethods.loadPrintDevice(cb_0_Print);
        }

        //选择存货
        private void proClick(object sender, EventArgs e)
        {
            var selectInv = new SelectInventory();
            CommonMethods.Parameters = null;
            selectInv.ShowDialog();

            if (CommonMethods.Parameters != null)
            {
                var pars = CommonMethods.Parameters;

                tb_proCode.Text = pars["proCode"];
                tb_proName.Text = pars["proName"];
                tb_spec.Text = pars["spec"];
            }
        }

        //选择检验员
        private void ppClick(object sender, EventArgs e)
        {
            var selectUser = new SelectUser();
            CommonMethods.Parameters = null;
            selectUser.ShowDialog();

            if (CommonMethods.Parameters != null)
            {
                var pars = CommonMethods.Parameters;

                checkPpCode.Text = pars["userCode"];
                checkPp.Text = pars["userName"];
            }
        }


        // 启动串口读取
        void StartSerialReading()
        {
            try
            {
                var portName = ConfigurationSettings.AppSettings["PortName"];
                var bautRate = ConfigurationSettings.AppSettings["BautRate"];
                var dataBits = ConfigurationSettings.AppSettings["DataBits"];


                serial = new SerialPortStream(portName, int.Parse(bautRate), int.Parse(dataBits), Parity.None, StopBits.One);
                serial.DataReceived += serial_DataReceived;
                serial.Open();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("串口启动失败，错误信息：" + ex.Message);
            }
        }

        bool ShouldReadingData = true;  //是否需要读取（称）数据

        // 串口读取数据的回调方法
        void serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (!ShouldReadingData)
            {
                return;//达到开关串口效果
            }

            var displayNum = 0.0m;

            var receivedStr = serial.ReadExisting();

            //int plusIndex = receivedStr.IndexOf("+");

            //// 如果加号不存在
            //if (plusIndex < 0)
            //{
            //    return;
            //}

            //// 如果加号后的字符位数，小于6
            //if (receivedStr.Length < plusIndex + 6)
            //{
            //    return;
            //}

            //var subStr = receivedStr.Substring(plusIndex, 7);
            //decimal.TryParse(subStr.TrimStart('+'), out displayNum);   

            //XtraMessageBox.Show(receivedStr);

            int plusIndex = receivedStr.IndexOf("wn");

            // 如果"wn"不存在
            if (plusIndex < 0)
            {
                return;
            }

            // 如果"w"后的字符位数，小于10
            if (receivedStr.Length < plusIndex + 10)
            {
                return;
            }

            var subStr = receivedStr.Substring(plusIndex+2, 8);

            //XtraMessageBox.Show(subStr);  //000340.0
            decimal.TryParse(subStr, out displayNum);

            //displayNum /= 100.0m;

            // 从另一个线程访问主线程
            this.Invoke(new Action(() =>
            {
                tb_realWeight.Text = displayNum.ToString("0.0");

                CalculateProWeight();
            }));
        }

        // 自动计算净重
        void CalculateProWeight()
        {
            if (!string.IsNullOrEmpty(tb_realWeight.Text) && !string.IsNullOrEmpty(cb_boxWeight.Text))
            {
                var realWeightValue = decimal.Parse(tb_realWeight.Text);
                //var match = Regex.Match(cb_boxWeight.Text.ToString(), @"(\d+(\.\d+)?)|(\.\d+)").Value;
                var match = "0";
                var sql = @"select cMemo from [fun_CommonData_Info] 
where cType = 'TubeWeight' and parentCode = '3' and isDel = 0 and [status] = 'Y' and cCode = '" + cb_boxWeight.SelectedValue.ToString() + "' ;";
                var table = db.getData(sql);
                if (table.Rows.Count > 0)
                {
                    match = table.Rows[0]["cMemo"].ToString();
                    boxNum.Text = match;
                }
                var boxWeightValue = decimal.Parse(match);

                tb_proWeight.Text = (realWeightValue - boxWeightValue).ToString();
            }
        }
       

        static void StartNewProgramByCreateFlags(string exePath)
        {
            using (var managementClass = new ManagementClass("Win32_Process"))
            {
                var processInfo = new ManagementClass("Win32_ProcessStartup");

                processInfo.Properties["CreateFlags"].Value = 0x00000008;
                processInfo.Properties["ShowWindow"].Value = 0x00000001;

                var inParameters = managementClass.GetMethodParameters("Create");
                //inParameters["CommandLine"] = "notepad.exe";
                inParameters["CommandLine"] = exePath;
                inParameters["ProcessStartupInformation"] = processInfo;

                var result = managementClass.InvokeMethod("Create", inParameters, null);
                if ((result != null) && ((uint)result.Properties["ReturnValue"].Value != 0))
                {
                    Console.WriteLine("Process ID: {0}", result.Properties["ProcessId"].Value);
                }
            }
        }

        private void cb_boxWeight_SelectedValueChanged(object sender, EventArgs e)
        {
            CalculateProWeight();
        }

        // 获取初始仓库编码
        string GetInitWarehouseCode()
        {
            var sql = "select * from sys_parameters_info where parCode = 'InitWarehouseCode'";
            var dt = db.getData(sql);

            return dt.Rows[0]["parValue"].ToString();
        }

        // 开始打印的方法
        private void barBtn_Print_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            #region 必填验证
            if (string.IsNullOrWhiteSpace(cb_boxWeight.Text))//
            {
                XtraMessageBox.Show("请选择轴管");
                return;
            }

            if (string.IsNullOrWhiteSpace(tb_proName.Text))//
            {
                XtraMessageBox.Show("请选择存货信息");
                return;
            }
            if (string.IsNullOrWhiteSpace(tb_mIng.Text))
            {
                XtraMessageBox.Show("请录入主要成分");
                return;
            }
            if (string.IsNullOrWhiteSpace(tb_grade.Text))
            {
                XtraMessageBox.Show("请录入等级");
                return;
            }
            if (string.IsNullOrWhiteSpace(tb_standard.Text))
            {
                XtraMessageBox.Show("请录入执行标准");
                return;
            } 
            if (string.IsNullOrWhiteSpace(tb_address.Text))
            {
                XtraMessageBox.Show("请录入公司地址");
                return;
            }
            if (string.IsNullOrWhiteSpace(tb_phone.Text))
            {
                XtraMessageBox.Show("请录入电话");
                return;
            }
            if (string.IsNullOrWhiteSpace(teams.Text))
            {
                XtraMessageBox.Show("请选择班次");
                return;
            }
            if (string.IsNullOrWhiteSpace(tb_Date.Text))
            {
                XtraMessageBox.Show("请选择生产日期");
                return;
            }
            if (string.IsNullOrWhiteSpace(tb_wareHouse.Text))
            {
                XtraMessageBox.Show("请选择入库仓库");
                return;
            }
            //if (string.IsNullOrWhiteSpace(checkPp.Text))
            //{
            //    XtraMessageBox.Show("请选择检验员");
            //    return;
            //}

            if (decimal.Parse(tb_proWeight.Text) < 0.0m)//
            {
                XtraMessageBox.Show("打印净重必须大于等于0.0");
                return;
            }

            #endregion


            // 检查数量数量是否超限
            foreach (var pm in printModels)
            {
                if (pm.printedNum + pm.number > pm.planNum)
                {
                    MessageBox.Show("打印数量已超过计划数量，无法打印");
                    return;
                }
            }


            Dictionary<string, string> barDic = new Dictionary<string, string>();

            barDic["proCode"] = tb_proCode.Text;//存货编码
            barDic["proName"] = tb_proName.Text;//存货名称
            barDic["wareHouse"] = tb_wareHouse.SelectedValue.ToString();//仓库编码
            barDic["barStatus"] = "need_out";
            barDic["proWeight"] = tb_proWeight.Text;//净重
            barDic["maoWeight"] = tb_realWeight.Text;//毛重
            //barDic["boxWeight"] = cb_boxWeight.SelectedValue.ToString();//轴管
            barDic["zhouName"] = cb_boxWeight.Text;//轴管名称
            barDic["zhouWeight"] = boxNum.Text;//轴重
            //barDic["boxWeight"] = cb_boxWeight.SelectedValue.ToString();//轴管
            barDic["spec"] = tb_spec.Text;//规格
            barDic["happenDate"] = tb_Date.Text;//发生日期
            if (yaGuang.Checked)
            {
                barDic["yaGuang"] = "是";//是否压光（是）
            }
            else
            {
                barDic["yaGuang"] = "否";//是否压光（否）
            }
            barDic["chengfen"] = tb_mIng.Text;//主要成分
            barDic["grade"] = tb_grade.Text;//等级
            barDic["standard"] = tb_standard.Text;//标准
            barDic["address"] = tb_address.Text;//地址
            barDic["phone"] = tb_phone.Text;//电话
            barDic["checkCode"] = checkPpCode.Text;//检验人员编码
            barDic["checkNmae"] = checkPp.Text;//检验人员名称
            barDic["Department"] = teams.SelectedValue.ToString();//班次
            barDic["createuser"] = CommonMethods.userCode;//打码人员
            if (cbIsPrint.Checked)
            {
                barDic["isInitial"] = "Y";
            }
            else
            {
                barDic["isInitial"] = "N";
            }

            var msg = http.PostJson("SaveBarCode", JsonConvert.SerializeObject(barDic));
            
            var json = JsonConvert.DeserializeObject<ReturnResult>(msg);
            //var json = JsonConvert.DeserializeObject<ReturnResult>(msg);
            if (json.Result)
            {
                if (json.Data==null || string.IsNullOrWhiteSpace(json.Data.ToString()))
                {
                    MessageBox.Show("接口返回数据异常，请联系开发人员！（"+json.Message+"）", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                var table = CommonMethods.createPrintTable();
                StringBuilder yin = new StringBuilder();
                yin.Append(" select * from V_BarCode_Info where barCode = '" + json.Data.ToString() + "' ");
                var pTable = db.getData(yin.ToString(), "");
                #region 填充表格数据
                var r = table.NewRow();
                r["barCode"] = pTable.Rows[0]["barCode"].ToString();
                r["proName"] = pTable.Rows[0]["proName"].ToString();
                r["yaGuang"] = pTable.Rows[0]["yaGuang"].ToString();
                r["proCode"] = pTable.Rows[0]["proCode"].ToString();
                r["spec"] = pTable.Rows[0]["spec"].ToString();
                r["chengfen"] = pTable.Rows[0]["chengfen"].ToString();
                r["maoWeight"] = pTable.Rows[0]["maoWeight"].ToString();
                r["proWeight"] = pTable.Rows[0]["proWeight"].ToString();
                r["grade"] = pTable.Rows[0]["grade"].ToString();
                r["happenDate"] = pTable.Rows[0]["happenDate"].ToString();
                r["checkCode"] = pTable.Rows[0]["checkCode"].ToString();
                r["checkName"] = pTable.Rows[0]["checkName"].ToString();
                r["Department"] = pTable.Rows[0]["Department"].ToString();
                r["deptName"] = pTable.Rows[0]["deptName"].ToString();
                r["standard"] = pTable.Rows[0]["standard"].ToString();
                r["address"] = pTable.Rows[0]["address"].ToString();
                r["phone"] = pTable.Rows[0]["phone"].ToString();
                table.Rows.Add(r);
                #endregion
                string info = "";
                var pResult = CommonMethods.DoPrint(table, cb_0_Template.Text, cb_0_Print.Text, ref info);
                if (!pResult)
                {
                    MessageBox.Show("条码打印失败：" + info, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                //MessageBox.Show("接口反馈异常", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                MessageBox.Show(json.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void barBtn_barCodeList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //XtraDialogForm form = new XtraDialogForm();
            //form.Shown += form_Shown;

            //BarCodeListControl myControl = new BarCodeListControl();
            ////XtraDialogArgs args = new XtraDialogArgs(null, myControl, "已打印条码", new[] { DialogResult.Yes, DialogResult.No, DialogResult.Abort, DialogResult.Ignore, DialogResult.Retry }, 0);
            //XtraDialogArgs args = new XtraDialogArgs(null, myControl, "已打印条码", new[] { DialogResult.Yes, DialogResult.No }, 0);
            //args.Showing += (showSender, showE) =>
            //{
            //    showE.Buttons[DialogResult.Yes].Text = "选中条码入库";
            //    showE.Buttons[DialogResult.Yes].Width = 100;
            //    showE.Buttons[DialogResult.Yes].Height = 30;

            //    showE.Buttons[DialogResult.No].Text = "取消";
            //    showE.Buttons[DialogResult.No].Width = 100;
            //    showE.Buttons[DialogResult.No].Height = 30;
            //    //showE.Buttons[DialogResult.Abort].Text = "GoodBye";
            //    //showE.Buttons[DialogResult.Abort].Width = 320;
            //    //showE.Buttons[DialogResult.Retry].Text = "Hello";
            //    //showE.Buttons[DialogResult.Ignore].Text = "What?";
            //};
            //if (form.ShowMessageBoxDialog(args) == DialogResult.OK)
            //{
            //    /*
            //    * string login = myControl.Login;
            //    * string password = myControl.Password;
            //    */
            //}

            var form = new PrintedBarListForm();
            form.ShowDialog();
        }

        private void barBtn_Update_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var updateProgramFullPath = ConfigurationManager.AppSettings["UpdaterPath"];

            StartNewProgramByCreateFlags("cmd /C " + updateProgramFullPath + " " + Environment.GetCommandLineArgs()[1]);

            Application.Exit();
        }

        void CheckVersion()
        {
            //http://localhost:2824/service/GetLastVersionString
            var url = ConfigurationManager.AppSettings["serUrl"] + "GetLastVersionString";
            string newVersion = http.Get(url, "");

            string currentVersion = Application.ProductVersion;


            if (string.Compare(newVersion, currentVersion) > 0)
            {
                this.Invoke(new Action(() =>
                {
                    barItem_LatestVersionNoti.Caption = "发现新版本:" + newVersion;
                }));

            }
            else
            {
                this.Invoke(new Action(() =>
                {
                    barItem_LatestVersionNoti.Caption = "当前已是最新版本";
                }));
            }
        }

        private void barBtn_Exit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            serial.Close();
            serial.Dispose();
            Application.Exit();
        }


        private void barItem_UpdateTemplate_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                var url = ConfigurationManager.AppSettings["serUrl"] + "GetTemplateFileZip";

                var downloadFolder = ConfigurationManager.AppSettings["currentPath"];

                var templateFolder = downloadFolder + "\\" + "Template";

                System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(templateFolder);

                directory.Empty();

                var compressedFile = url.DownloadFileAsync(downloadFolder).Result;

                ZipFile.ExtractToDirectory(compressedFile, templateFolder);

                XtraMessageBox.Show("打印模板更新成功");
            }
            catch (Exception ex)
            {

                XtraMessageBox.Show("抱歉,更新失败：" + ex.Message);
            }
        }


        private void tb_realWeight_EditValueChanged(object sender, EventArgs e)
        {
            CalculateProWeight();
        }

        private void cb_boxWeight_TextChanged(object sender, EventArgs e)
        {
            CalculateProWeight();
        }

        private void btn_open_Click(object sender, EventArgs e)
        {
            ShouldReadingData = true;
            label1.Text = "串口已打开";
        }

        private void btn_close_Click(object sender, EventArgs e)
        {
            ShouldReadingData = false;
            label1.Text = "串口已关闭";
        }

    }

    class DictionaryAsArrayResolver : DefaultContractResolver
    {
        protected override JsonContract CreateContract(Type objectType)
        {
            if (objectType.GetInterfaces().Any(i => i == typeof(IDictionary<,>) ||
                (i.IsGenericType &&
                 i.GetGenericTypeDefinition() == typeof(IDictionary<,>))))
            {
                return base.CreateArrayContract(objectType);
            }

            return base.CreateContract(objectType);
        }
    }

    public class BarCodeListControl : XtraUserControl
    {
        DBHelper db = new DBHelper();

        TextEdit teLogin;
        TextEdit tePassword;
        public BarCodeListControl()
        {
            LayoutControl lc = new LayoutControl();
            lc.Dock = DockStyle.Fill;

            //this.teLogin = new TextEdit();
            //this.tePassword = new TextEdit();
            //tePassword.Properties.UseSystemPasswordChar = true;
            //CheckEdit ceKeep = new CheckEdit() { Text = "Keep me signed in" };

            //lc.AddItem(String.Empty, teLogin).TextVisible = false;
            //lc.AddItem(String.Empty, tePassword).TextVisible = false;
            //lc.AddItem(String.Empty, ceKeep);

            var sql_temp = "select * from bar_ProductBarCode_info where createuser = '{0}' and isInitial = 'N' and status = 'Y' and barStatus = 'need-in';";
            var sql = string.Format(sql_temp, CommonMethods.userCode);

            var grid_BarCode = new GridControl();


            grid_BarCode.DataSource = CommonMethods.ConvertTo<BarCodeListModel>(db.getData(sql));

            grid_BarCode.Dock = DockStyle.Fill;


            lc.AddItem(string.Empty, grid_BarCode);

            this.Controls.Add(lc);

            this.Size = new Size { Width = 800, Height = 600 };

            //this.Height = 600;

            this.Dock = DockStyle.Top;

            //grid_BarCode.Width = 400;
            //grid_BarCode.Height = 600;
            // 会引发未将对象引用到实例

            //var mainView = grid_BarCode.MainView as GridView;
            //mainView.OptionsView.ShowGroupPanel = false;

        }

    }


}

namespace ExtensionMethods
{
    public static class MyExtensions
    {
        // 清空文件夹的方法
        static public void Empty(this System.IO.DirectoryInfo directory)
        {
            foreach (System.IO.FileInfo file in directory.GetFiles()) file.Delete();
            foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
        }
    }
}

